﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net.Sockets;
using System.Net;
using System.IO;

namespace wpfSocketRecv
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            m_listenerSocket = ConnectSocket();
            m_listenerSocket.Listen(100);

            m_bwListener = new BackgroundWorker();
            m_bwListener.WorkerSupportsCancellation = true;
            m_bwListener.DoWork += new DoWorkEventHandler(m_bwListener_DoWork);
            m_bwListener.RunWorkerAsync();
        }

        private List<BackgroundWorker> m_listBW = new List<BackgroundWorker>();
        private const long m_FILESIZE = 5241600;

        void m_bwListener_DoWork(object sender, DoWorkEventArgs e)
        {
            int i = 0;

            while (true)
            {
                Socket clientSock = m_listenerSocket.Accept();
                BWSArgs bws = new BWSArgs 
                { 
                    ClientSock = clientSock, 
                    FileName = string.Format("Files\\{0}.txt", i),
                    FileSize = m_FILESIZE 
                };

                BackgroundWorker bw = new BackgroundWorker();
                bw.WorkerSupportsCancellation = true;
                bw.DoWork += new DoWorkEventHandler(bw_DoWork);
                bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
                m_listBW.Add(bw);
                bw.RunWorkerAsync(bws);
                ++i;
            }
        }

        void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            BackgroundWorker bw = sender as BackgroundWorker;
            BWSArgs bws = e.Result as BWSArgs;
            bws.ClientSock.Close();
            m_listBW.Remove(bw);
        }

        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BWSArgs bws = e.Argument as BWSArgs;
            byte[] data = new byte[bws.FileSize];
            bws.ClientSock.Receive(data);

            BinaryWriter bWrite = new BinaryWriter(File.Open(bws.FileName, FileMode.OpenOrCreate)); ;
            bWrite.Write(data, 0, data.Length);
            bWrite.Close();
            e.Result = bws;
        }

        private Socket m_listenerSocket;
        private BackgroundWorker m_bwListener;

        private Socket ConnectSocket()
        {
            Socket s = null;
            IPEndPoint hostEntry = null;

            hostEntry = new IPEndPoint(IPAddress.Any, 5658);
            s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            s.Bind(hostEntry);

            return s;
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            if (m_listBW.Count > 0)
            {
                MessageBox.Show("There are files still transfering");
                e.Cancel = true;
            }
            else
            {
                m_listenerSocket.Close();
            }
        }
    }

    public class BWSArgs
    {
        public Socket ClientSock { get; set; }
        public string FileName { get; set; }
        public long FileSize { get; set; }
    }
}
